/*
 * Group 3, User Interface Programming II (vt11)
 * Pooya | Flora | Monica | Can
 */
package vical.view;

import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import vical.controller.PreferenceController;
import vical.data.DataManager;

/**
 * The window listener to deal with common features for all windows type
 * Like saving size and location
 * 
 * @author Can
 */
public class SmartWindowListener extends WindowAdapter {

    @Override
    public void windowClosing(WindowEvent e) {
        Object object = e.getSource();
        if (object instanceof Frame) {
            saveFrameParameters((Frame) object);
        } else if (object instanceof Dialog) {
            saveDialogParameters((Dialog) object);
        }
        super.windowClosing(e);
    }

    @Override
    public void windowOpened(WindowEvent e) {
        Window window = e.getWindow();
        window.setSize(PreferenceController.getSize(window.getClass().getName()));
        window.setLocation(PreferenceController.getLocation(window.getClass().getName()));
        Object object = e.getSource();
        if (object instanceof Frame) {
            ((Frame)object).setExtendedState(
                    PreferenceController.getExtendedState(object.getClass().getName(), Frame.NORMAL));
        }
        super.windowOpened(e);
    }

    private void saveFrameParameters(Frame frame) {
        // TODO: Pooya, it should be saved after each modification, not in the end!
        DataManager.getInstance().save();

        if ((frame.getExtendedState() & Frame.MAXIMIZED_BOTH) != Frame.MAXIMIZED_BOTH) {
            saveWindowParameters(frame);
        }
        PreferenceController.setExtendedState(frame.getClass().getName(), frame.getExtendedState());
    }

    private void saveDialogParameters(Dialog dialog) {
        // TODO: Pooya, it should be saved after each modification, not in the end!
        DataManager.getInstance().save();

        saveWindowParameters(dialog);
    }

    private void saveWindowParameters(Window window) {
        PreferenceController.setSize(window.getClass().getName(), window.getSize());
        PreferenceController.setLocation(window.getClass().getName(), window.getLocation());
    }
}
